package com.zenkeeuk.bookerfornfc.client.android;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.zenkeeuk.bookerfornfc.client.android.book.LabBookHistoryInfo;
import com.zenkeeuk.bookerfornfc.client.android.book.LabBookInfo;
import com.zenkeeuk.bookerfornfc.client.android.book.LabBookListAdapter;
import com.zenkeeuk.bookerfornfc.client.android.service.BookerCheckService;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;

public class LabBookNoticeActivity extends Activity {
	
	private List<LabBookInfo> listResilt;
	private List<LabBookInfo> sortedlistResilt;
	private List<LabBookInfo> sortedReturnedlistResilt;
	private List<LabBookInfo> sortedNotReturnedlistResilt;
	private BookerCheckService.GetLabInfoBinder binder;
    private boolean binded;
    private int iBookReturned = 0;
	private int iBookUpToDate = 0;
      
    private Handler handler = new Handler() {  
        public void handleMessage(android.os.Message msg) {
        	if (msg.what == 1) {
        		TextView notice_summary = (TextView)findViewById(R.id.notice_summary);
        		notice_summary.setText("您关注的图书中，有"+iBookReturned+"本图书已经归还，"+iBookUpToDate+"本图书接近还书时间！");
        		
        		ListView lv = (ListView) findViewById(R.id.notice_list);
        		LabBookListAdapter listAdapter;
        		if (sortedlistResilt.size() > 0) {
        			listAdapter = new LabBookListAdapter(LabBookNoticeActivity.this, sortedlistResilt);
        		} else {
        			listAdapter = null;
        		}
        		
        		lv.setAdapter(listAdapter);
        	}
        };  
    };
    
    private ServiceConnection conn = new ServiceConnection() {  
        
        public void onServiceConnected(ComponentName name, IBinder service) {  
            binder = (BookerCheckService.GetLabInfoBinder) service;  
            
            listenProgress();  
        }  
          
        public void onServiceDisconnected(ComponentName name) {  
        }  
    }; 
	
	@Override
	public void onCreate(Bundle icicle) {
	    super.onCreate(icicle);
	    requestWindowFeature(Window.FEATURE_NO_TITLE);
	    setContentView(R.layout.labbooknotice);
	    
	  //绑定service  
        Intent intent = new Intent(this, BookerCheckService.class);  
        bindService(intent, conn, Context.BIND_AUTO_CREATE);  
        binded = true;  
	}
	
	@Override  
    protected void onDestroy() {  
        super.onDestroy();  
        //如果是绑定状态,则取消绑定  
        if (binded) {  
            unbindService(conn);  
        }
    }
	
	private void insertIntoSortedList(LabBookInfo book, boolean isReturned) {
		if (isReturned) {
			sortedReturnedlistResilt.add(book);
		} else {
			sortedNotReturnedlistResilt.add(book);
		}
	}
	
	private long convertDate(String date) {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date returntime = null;
		try {
			returntime = format.parse(date);
		} catch (ParseException e) {
			return -1;
		}
		
		return returntime.getTime();
	}
	
	public List<LabBookInfo> sortbooklist(List<LabBookInfo> values) {
		// 从此一个位开始循环数组 
		for(int i=0;i<values.size();i++){ 
			// 从第i+1为开始循环数组 
			for(int j=i+1;j<values.size();j++){ 
				// 如果前一位比后一位小，那么就将两个数字调换 
				// 这里是按降序排列 
				// 如果你想按升序排列只要改变符号即可 
				if (convertDate(values.get(i).getToReturnTime()) < convertDate(values.get(j).getToReturnTime())) {
					LabBookInfo temp = new LabBookInfo();
					temp = values.get(i);
					values.set(i, values.get(j));
					values.set(j, temp);
				}
			} 
		}
		return values;
	}
	
	private void listenProgress() {  
        new Thread() {
            public void run() {  
            	listResilt = binder.getlistResilt();
            	sortedlistResilt = new ArrayList<LabBookInfo>();
            	sortedReturnedlistResilt = new ArrayList<LabBookInfo>();
            	sortedNotReturnedlistResilt = new ArrayList<LabBookInfo>();            	
            	
                if (listResilt != null && listResilt.size() > 0) {
                	iBookReturned = 0;
                	iBookUpToDate = 0;
                	
                	if (listResilt != null) {
            	    	for(int i = 0;i<listResilt.size();i++) {
            	    		if (listResilt.get(i).getRemark().equals("未借")) {
            	    			iBookReturned ++;            	    			
            	    			insertIntoSortedList(listResilt.get(i), true);            	    			
            	    		} else if (listResilt.get(i).getRemark().equals("已借")) {
            	    			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            	    			Date returntime = null;
            	    			try {
            	    				returntime = format.parse(listResilt.get(i).getToReturnTime());
            	    			} catch (ParseException e) {
            	    				
            	    			}
            	    			
            	    			if (returntime != null) {
            	    				Date now = new Date();
            	    				long timegap = returntime.getTime() - now.getTime();
            	    				if (timegap > 0 && timegap < Contents.ALERT_BOOK_RETURN_EARLIER_TIME) {
            	    					iBookUpToDate ++;            	    					
            	    					insertIntoSortedList(listResilt.get(i), false);
            	    				}
            	    			}
            	    		}
            	    	}
                	}
                }
                
                sortedlistResilt.addAll(sortedReturnedlistResilt);
                sortedlistResilt.addAll(sortbooklist(sortedNotReturnedlistResilt));
            	
                Message msg = handler.obtainMessage();  
                msg.what = 1;
                handler.sendMessage(msg);  
                try {  
                    Thread.sleep(30000);  
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }                  
            };  
        }.start();  
    }  
}
